<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>班级数据管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getClassroomList" @keyup.enter="getClassroomList">
          <el-button slot="append" icon="el-icon-search" @click="getClassroomList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="addClassroomVisible = true">添加数据</el-button>
      </el-col>
      <el-col :span="2">
          <el-button type="primary" @click="addClassroomFormDialogVisible = true">批量导入</el-button>
        </el-col>
    </el-row>

      <!-- 班级列表区域 -->
      <el-table :data="ClassroomList" border stripe>	
        <el-table-column label="班级编号" prop="id"></el-table-column>
        <el-table-column label="班级名称" prop="name"></el-table-column>
        <el-table-column label="班级信息" prop="claMsg"></el-table-column>
        <el-table-column label="班主任" prop="teaName"></el-table-column>
        <el-table-column label="年级" prop="grade"></el-table-column>
        <el-table-column label="人数" prop="claNum"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditClassroom(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeClassroomById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNo"
        :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加班级的对话框 -->
    <el-dialog title="添加班级" :visible.sync="addClassroomVisible" width="50%" @close="addClassroomClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addClassroomForm" :rules="addClassroomFormRules" ref="addClassroomFormRef" label-width="70px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="addClassroomForm.name"></el-input>
        </el-form-item>
        <el-form-item label="班级信息" prop="message">
          <el-input v-model="addClassroomForm.message"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="teacherId">
          <el-select v-model="addClassroomForm.teacherId" placeholder="班主任">
              <el-option
                v-for="item in teacherList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="addClassroomForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="人数" prop="num">
          <el-input v-model="addClassroomForm.num"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassroomVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassroom">确 定</el-button>
      </span>

    </el-dialog>
    
        <el-dialog title="批量导入班级数据" :visible.sync="addClassroomFormDialogVisible" width="30%" @close="addClassroomFormDialogClosed">
      <el-form  ref="fileFormRef" :v-modle="fileForm">
        <el-form-item label="批量导入"   >
          <el-link  type="primary" href="http://120.27.233.52:8080/classroom.xlsx" >下载模板</el-link><br/>
          <input type="file"  @change="getFile($event)" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassroomFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassrooms">确 定</el-button>
      </span>

    </el-dialog>

    <!-- 修改班级的对话框 -->
    <el-dialog title="修改班级信息" :visible.sync="editClassroomVisible" width="50%" @close="editClassroomClosed">
      <el-form :model="editClassroomForm" :rules="editClassroomFormRules" ref="editClassroomFormRef" label-width="70px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="editClassroomForm.name"></el-input>
        </el-form-item>
        <el-form-item label="班级信息" prop="claMsg">
          <el-input v-model="editClassroomForm.claMsg"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="teaName">
          <el-select v-model="editClassroomForm.teaName" placeholder="班主任">
              <el-option
                v-for="item in teacherList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="editClassroomForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="人数" prop="clsNum">
          <el-input v-model="editClassroomForm.clsNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editClassroomVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClassroomInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

     return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pageNo:1,
        // 当前每页显示多少条数据
        pageSize:5
      },
      ClassroomList: [],

      total: 0,
      // 控制添加班级对话框的显示与隐藏
      addClassroomVisible: false,
      addClassroomFormDialogVisible: false,
      // 添加班级的表单数据
      addClassroomForm: {
          id: '',
          name: '',
          claMsg: '',
          teaName: '',
          grade:'',
          claNum:'',
      },
       fileForm:{
          file:'',
      },
      teacherList: [],
      fileList: [],
      // 添加表单的验证规则对象
      addClassroomFormRules: {
        username: [{
          required: true,
          message: '请输入班级名',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '班级名的长度在3~10个字符之间',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '班级名的长度在6~15个字符之间',
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ],
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }
        ]
      },
      // 控制修改班级对话框的显示与隐藏
      editClassroomVisible: false,
      // 查询到的班级信息对象
      editClassroomForm: {
          name: '',
          message: '',
          teacherId: '',
          grade:'',
          clsNum:'',
      },
      // 修改表单的验证规则对象
      editClassroomFormRules: {
        email: [{
          required: true,
          message: '请输入班级邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ],
        mobile: [{
          required: true,
          message: '请输入班级手机',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的班级信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getClassroomList()
    this.getTeacherList()
  },
  methods: {
    async getClassroomList() {
        const { data: res } = await this.$http.get('/classroom', {
            params: this.queryInfo
        })

        if (res.code !== 200) {
            return this.$message.error('获取班级列表失败！')
        }
        this.ClassroomList = res.data.info
        this.total = res.data.total
    },
    async getTeacherList() {
      this.teacherList = [{
        value: '2',
        label: '张乐乐'
      }, {
        value: '3',
        label: '123'
      }, {
          value: '4',
          label: '123'
      }, {
          value: '5',
          label: 'asd'
      }]
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getClassroomList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNo = newPage
      this.getClassroomList()
    },
    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      // const { data: res } = await this.$http.put(
      //   `users/${userinfo.id}/state/${userinfo.mg_state}`
      // )
      // if (res.meta.status !== 200) {
      //   userinfo.mg_state = !userinfo.mg_state
      //   return this.$message.error('更新班级状态失败！')
      // }
      this.$message.success('更新班级状态成功！')
    },
    // 监听添加班级对话框的关闭事件
    addClassroomClosed() {
      this.$refs.addClassroomFormRef.resetFields()
    },
    // 点击按钮，添加新班级
    addClassroom() {
      this.getTeacherList()
        let form = new FormData()
        form.append('name',this.addClassroomForm.name)
        form.append('message',this.addClassroomForm.message)
        form.append('teacherId',this.addClassroomForm.teacherId)
        form.append('grade',this.addClassroomForm.grade)
        form.append('num',this.addClassroomForm.num)
      this.$refs.addClassroomFormRef.validate(async valid => {
          if (!valid) return

          const { data: res } = await this.$http.post('/classroom', form)

          if (res.code !== 200) {
              this.$message.error('添加班级失败！')
          }

          this.$message.success('添加班级成功！')
          // 隐藏添加班级的对话框
          this.addClassroomVisible = false
          // 重新获取班级列表数据
          this.getClassroomList()
      })
    },
    
    addClassroomFormDialogClosed() {
                this.$refs.fileFormRef.resetFields()
            },
            async addClassrooms() {
                var formData = new FormData()
                formData.append('file', this.fileForm.file)


                    const { data: res } = await this.$http.post('/Upload/classImportExcel',formData,{
                            headers:{
                                'Content-Type':'multipart/form-data'
                            },
                        }
                    )
                    console.log(res)
                    if (res.code !== 200) {
                        this.$message.error('批量导入失败！')
                    }

                    this.$message.success('批量导入成功！')
                    this.addClassroomFormDialogVisible = false
                    this.getClassroomList()

            },
            getFile(event){
                this.fileForm.file = event.target.files[0]
                console.log(this.fileForm.file)
            },
    
    // 展示编辑班级的对话框
      async showeditClassroom(id) {
          const { data: res } = await this.$http.get('/classroom/'+ id)
          if (res.code !== 200) {
              return this.$message.error('查询班级信息失败！')
          }

          this.editClassroomForm = res.data

          this.editClassroomVisible = true
      },
    // 监听修改班级对话框的关闭事件
    editClassroomClosed() {
      this.$refs.editClassroomFormRef.resetFields()
    },
    // 修改班级信息并提交
      editClassroomInfo() {
          let form = new FormData()
          form.append('id',this.editClassroomForm.id)
          form.append('teacherId',this.editClassroomForm.teaName)
          form.append('claMsg',this.editClassroomForm.claMsg)
          form.append('grade',this.editClassroomForm.grade)
          form.append('clsNum',this.editClassroomForm.clsNum)
          form.append('name',this.editClassroomForm.name)
          console.log(this.editClassroomForm)
          this.$refs.editClassroomFormRef.validate(async valid => {
              if (!valid) return
              const  { data: res } = await this.$http.put( 'classroom', form )

              if (res.code !== 200) {
                  return this.$message.error(res.msg)
              }

              // 关闭对话框
              this.editClassroomVisible = false
              // 刷新数据列表
              this.getClassroomList()
              // 提示修改成功
              this.$message.success('更新班级信息成功！')
          })
      },
      // 根据Id删除对应的班级信息
      async removeClassroomById(id) {
          // 弹框询问班级是否删除数据
          const confirmResult = await this.$confirm(
              '此操作将永久删除该班级, 是否继续?',
              '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }
          ).catch(err => err)

          // 如果班级确认删除，则返回值为字符串 confirm
          // 如果班级取消了删除，则返回值为字符串 cancel
          // console.log(confirmResult)
          if (confirmResult !== 'confirm') {
              return this.$message.info('已取消删除')
          }

          const {data: res} = await this.$http.delete('/classroom/'+ id )

          if (res.code !== 200) {
              return this.$message.error('删除班级失败！')
          }

          this.$message.success('删除班级成功！')
          this.getClassroomList()
      },

    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(this.fileList)
      console.log(file.response)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      console.log(fileList.slice(-3))
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
